package com.shkco.org.controller;

import com.shkco.basic.util.PageList;
import com.shkco.basic.util.AjaxResult;
import com.shkco.org.domain.Department;
import com.shkco.org.query.DepartmentQuery;
import com.shkco.org.service.IDepartmentService;
import com.shkco.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(value = "部门的API",description="部门相关的CRUD功能")
@RequestMapping("/department")
@RestController
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation(value = "通过ID查询" )
    @GetMapping("/{id}")
    @PreAuthorize(name = "获取部门",sn = "department:findById")
    public Department findById(@PathVariable("id")Long id){
        return departmentService.findById(id);
    }

    @ApiOperation(value = "查询所有" )
    @GetMapping
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    @ApiOperation(value = "根据id删除部门" )
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "删除部门",sn = "department:delete")
    public AjaxResult del(@PathVariable("id")Long id){
        try {
            departmentService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @ApiOperation(value = "新增或修改部门" )
    @PutMapping
    public AjaxResult addOrUpt(@ApiParam(name="部门",required = true)@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.add(department);
            } else {
                departmentService.update(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    @ApiOperation(value = "分页查询" )
    @PostMapping
    public PageList<Department> pageQuery(@ApiParam(name="分页数据",required = true)@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    @ApiOperation(value = "批量删除" )
    @PatchMapping
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }


    @ApiOperation(value = "查询部门树" )
    @GetMapping("/deptTree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }

}
